// pages/volunteer/activities.js
Page({
  data: {
    // 筛选状态
    selectedRegion: 'all',
    selectedService: 'all',
    selectedSort: 'latest',
    selectedDate: 'all',
    
    // 加载状态
    loading: false,
    hasMore: true,
    
    // 活动数据
    activities: [
      {
        id: '1',
        title: '8.24小小志愿者选拔志愿服务',
        organization: '阜阳市城市规划展示馆',
        image: '/images/1.jpg',
        participants: 0,
        maxParticipants: 5,
        distance: '>50km',
        district: '颍州区',
        status: 'recruiting',
        statusText: '招募中',
        tags: ['儿童教育', '文化传播'],
        date: '2024-08-24',
        serviceType: 'education'
      },
      {
        id: '2',
        title: '敬老润我心,服务献爱心',
        organization: '颍东区三助志愿者服务队',
        image: '/images/1.jpg',
        participants: 13,
        maxParticipants: 20,
        distance: '>50km',
        district: '颍东区',
        status: 'recruiting',
        statusText: '招募中',
        tags: ['敬老服务', '社区服务'],
        date: '2024-08-25',
        serviceType: 'elderly'
      },
      {
        id: '3',
        title: '"清厕焕新"清除城区公厕、小区非法小广告公益行动',
        organization: '界首市阳帆志愿者协会',
        image: '/images/1.jpg',
        participants: 7,
        maxParticipants: 200,
        distance: '>50km',
        district: '界首市',
        status: 'recruiting',
        statusText: '招募中',
        tags: ['环保', '城市清洁'],
        date: '2024-08-26',
        serviceType: 'environment'
      },
      {
        id: '4',
        title: '焦陂镇2025年暑期大学生村务实习志愿服务项目招募',
        organization: '阜南青志协焦陂青年志愿服务队',
        image: '/images/1.jpg',
        participants: 16,
        maxParticipants: 200,
        distance: '>50km',
        district: '阜南县',
        status: 'recruiting',
        statusText: '招募中',
        tags: ['实习项目', '乡村振兴'],
        date: '2024-08-27',
        serviceType: 'rural'
      },
      {
        id: '5',
        title: '招募老兵口述史的整理记录者',
        organization: '阜阳智合济困公益协会',
        image: '/images/1.jpg',
        participants: 22,
        maxParticipants: 10,
        distance: '>50km',
        district: '颍州区',
        status: 'full',
        statusText: '已满员',
        tags: ['历史记录', '口述史'],
        date: '2024-08-28',
        serviceType: 'culture'
      },
      {
        id: '6',
        title: '2025年8月六院门诊爱心志愿活动',
        organization: '阜阳市妇女儿童医院',
        image: '/images/1.jpg',
        participants: 105,
        maxParticipants: 150,
        distance: '>50km',
        district: '颍州区',
        status: 'recruiting',
        statusText: '招募中',
        tags: ['医疗健康', '爱心服务'],
        date: '2024-08-29',
        serviceType: 'medical'
      }
    ],
    
    // 筛选后的活动列表
    filteredActivities: [],
    
    // 筛选选项
    regions: [
      { value: 'all', text: '全部区域' },
      { value: 'yingzhou', text: '颍州区' },
      { value: 'yingdong', text: '颍东区' },
      { value: 'yingquan', text: '颍泉区' },
      { value: 'jieshou', text: '界首市' },
      { value: 'funan', text: '阜南县' }
    ],
    
    services: [
      { value: 'all', text: '全部领域' },
      { value: 'education', text: '教育服务' },
      { value: 'elderly', text: '敬老服务' },
      { value: 'environment', text: '环保服务' },
      { value: 'medical', text: '医疗健康' },
      { value: 'culture', text: '文化传播' },
      { value: 'rural', text: '乡村振兴' }
    ],
    
    sortOptions: [
      { value: 'latest', text: '最新发布' },
      { value: 'popular', text: '最受欢迎' },
      { value: 'nearby', text: '距离最近' },
      { value: 'deadline', text: '截止时间' }
    ]
  },

  onLoad: function (options) {
    console.log('活动页面加载');
    this.initData();
  },

  onShow: function () {
    // 页面显示时刷新数据
    this.loadActivities();
  },

  // 初始化数据
  initData: function () {
    this.filterActivities();
  },

  // 加载活动数据
  loadActivities: function () {
    console.log('加载活动数据');
    // 这里可以从服务器获取活动数据
    this.filterActivities();
  },

  // 筛选活动
  filterActivities: function () {
    let filtered = [...this.data.activities];
    
    // 按区域筛选
    if (this.data.selectedRegion !== 'all') {
      filtered = filtered.filter(item => {
        const regionMap = {
          'yingzhou': '颍州区',
          'yingdong': '颍东区',
          'yingquan': '颍泉区',
          'jieshou': '界首市',
          'funan': '阜南县'
        };
        return item.district === regionMap[this.data.selectedRegion];
      });
    }
    
    // 按服务领域筛选
    if (this.data.selectedService !== 'all') {
      filtered = filtered.filter(item => item.serviceType === this.data.selectedService);
    }
    
    // 按日期筛选
    if (this.data.selectedDate !== 'all') {
      const dateMap = {
        'today': '2024-08-22',
        'saturday': '2024-08-23',
        'sunday': '2024-08-24',
        'monday': '2024-08-25',
        'tuesday': '2024-08-26',
        'wednesday': '2024-08-27',
        'thursday': '2024-08-28'
      };
      filtered = filtered.filter(item => item.date === dateMap[this.data.selectedDate]);
    }
    
    // 排序
    filtered = this.sortActivities(filtered);
    
    this.setData({
      filteredActivities: filtered
    });
  },

  // 排序活动
  sortActivities: function (activities) {
    const sortType = this.data.selectedSort;
    
    switch (sortType) {
      case 'latest':
        return activities.sort((a, b) => new Date(b.date) - new Date(a.date));
      case 'popular':
        return activities.sort((a, b) => b.participants - a.participants);
      case 'nearby':
        return activities.sort((a, b) => {
          const distanceA = parseInt(a.distance.replace('>', '').replace('km', ''));
          const distanceB = parseInt(b.distance.replace('>', '').replace('km', ''));
          return distanceA - distanceB;
        });
      case 'deadline':
        return activities.sort((a, b) => new Date(a.date) - new Date(b.date));
      default:
        return activities;
    }
  },

  // 选择日期
  selectDate: function (e) {
    const date = e.currentTarget.dataset.date;
    this.setData({
      selectedDate: date
    });
    this.filterActivities();
  },

  // 显示区域筛选
  showRegionFilter: function (e) {
    const region = e.currentTarget.dataset.region;
    this.setData({
      selectedRegion: region
    });
    this.filterActivities();
  },

  // 显示服务领域筛选
  showServiceFilter: function (e) {
    const service = e.currentTarget.dataset.service;
    this.setData({
      selectedService: service
    });
    this.filterActivities();
  },

  // 显示排序筛选
  showSortFilter: function (e) {
    const sort = e.currentTarget.dataset.sort;
    this.setData({
      selectedSort: sort
    });
    this.filterActivities();
  },

  // 显示搜索
  showSearch: function () {
    wx.showModal({
      title: '搜索活动',
      content: '请输入活动关键词',
      editable: true,
      placeholderText: '如：敬老、环保、教育等',
      success: (res) => {
        if (res.confirm && res.content) {
          this.searchActivities(res.content);
        }
      }
    });
  },

  // 搜索活动
  searchActivities: function (keyword) {
    const filtered = this.data.activities.filter(item => 
      item.title.includes(keyword) || 
      item.organization.includes(keyword) ||
      item.tags.some(tag => tag.includes(keyword))
    );
    
    this.setData({
      filteredActivities: filtered
    });
    
    wx.showToast({
      title: `找到${filtered.length}个活动`,
      icon: 'success'
    });
  },

  // 显示更多筛选
  showMoreFilter: function () {
    wx.showActionSheet({
      itemList: ['按距离筛选', '按时间筛选', '按状态筛选', '重置筛选'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            this.filterByDistance();
            break;
          case 1:
            this.filterByTime();
            break;
          case 2:
            this.filterByStatus();
            break;
          case 3:
            this.resetFilters();
            break;
        }
      }
    });
  },

  // 按距离筛选
  filterByDistance: function () {
    wx.showActionSheet({
      itemList: ['5km以内', '10km以内', '20km以内', '50km以内'],
      success: (res) => {
        const distances = ['5km', '10km', '20km', '50km'];
        const maxDistance = distances[res.tapIndex];
        
        const filtered = this.data.activities.filter(item => {
          const distance = parseInt(item.distance.replace('>', '').replace('km', ''));
          return distance <= parseInt(maxDistance);
        });
        
        this.setData({
          filteredActivities: filtered
        });
      }
    });
  },

  // 按时间筛选
  filterByTime: function () {
    wx.showActionSheet({
      itemList: ['今天', '明天', '本周', '下周'],
      success: (res) => {
        // 这里可以实现具体的时间筛选逻辑
        wx.showToast({
          title: '时间筛选功能开发中',
          icon: 'none'
        });
      }
    });
  },

  // 按状态筛选
  filterByStatus: function () {
    wx.showActionSheet({
      itemList: ['招募中', '已满员', '已结束'],
      success: (res) => {
        const statuses = ['recruiting', 'full', 'ended'];
        const status = statuses[res.tapIndex];
        
        const filtered = this.data.activities.filter(item => item.status === status);
        
        this.setData({
          filteredActivities: filtered
        });
      }
    });
  },

  // 重置筛选
  resetFilters: function () {
    this.setData({
      selectedRegion: 'all',
      selectedService: 'all',
      selectedSort: 'latest',
      selectedDate: 'all'
    });
    this.filterActivities();
    
    wx.showToast({
      title: '筛选已重置',
      icon: 'success'
    });
  },

  // 查看活动详情
  viewActivityDetail: function (e) {
    const id = e.currentTarget.dataset.id;
    const activity = this.data.activities.find(item => item.id === id);
    
    if (activity) {
      // 先检查活动详情页面是否存在
      wx.navigateTo({
        url: `/pages/volunteer/activity-detail?id=${id}`,
        fail: (err) => {
          console.error('页面跳转失败:', err);
          // 如果页面不存在，显示活动信息弹窗
          this.showActivityInfo(activity);
        }
      });
    }
  },

  // 显示活动信息弹窗
  showActivityInfo: function (activity) {
    wx.showModal({
      title: activity.title,
      content: `组织方：${activity.organization}\n地点：${activity.district}\n参与人数：${activity.participants}/${activity.maxParticipants}人\n状态：${activity.statusText}`,
      confirmText: '立即报名',
      cancelText: '查看详情',
      success: (res) => {
        if (res.confirm) {
          this.joinActivity(activity);
        } else {
          // 这里可以跳转到详情页面或显示更多信息
          wx.showToast({
            title: '详情页面开发中',
            icon: 'none'
          });
        }
      }
    });
  },

  // 报名活动
  joinActivity: function (activity) {
    wx.showModal({
      title: '确认报名',
      content: `确定要报名参加"${activity.title}"吗？`,
      confirmText: '确定报名',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          // 检查是否已报名
          const userActivities = wx.getStorageSync('userActivities') || [];
          const isJoined = userActivities.some(ua => ua.activityId === activity.id);
          
          if (isJoined) {
            wx.showToast({
              title: '您已报名此活动',
              icon: 'none'
            });
            return;
          }
          
          // 检查是否还有名额
          if (activity.participants >= activity.maxParticipants) {
            wx.showToast({
              title: '活动已满员',
              icon: 'none'
            });
            return;
          }
          
          // 报名成功
          const newUserActivity = {
            activityId: activity.id,
            activityTitle: activity.title,
            joinTime: new Date().toISOString(),
            status: 'registered'
          };
          
          userActivities.push(newUserActivity);
          wx.setStorageSync('userActivities', userActivities);
          
          // 更新活动参与人数
          const activities = this.data.activities.map(item => {
            if (item.id === activity.id) {
              return { ...item, participants: item.participants + 1 };
            }
            return item;
          });
          
          this.setData({ activities });
          this.filterActivities();
          
          wx.showToast({
            title: '报名成功！',
            icon: 'success'
          });
        }
      }
    });
  },

  // 刷新活动
  refreshActivities: function () {
    this.setData({ loading: true });
    
    setTimeout(() => {
      this.loadActivities();
      this.setData({ loading: false });
      
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      });
    }, 1000);
  },

  // 加载更多活动
  loadMoreActivities: function () {
    this.setData({ loading: true });
    
    setTimeout(() => {
      // 模拟加载更多数据
      wx.showToast({
        title: '暂无更多活动',
        icon: 'none'
      });
      
      this.setData({ 
        loading: false,
        hasMore: false
      });
    }, 1000);
  },

  // 分享
  onShareAppMessage: function () {
    return {
      title: '找活动 - 志愿者活动',
      path: '/pages/volunteer/activities'
    };
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    this.refreshActivities();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  }
});